package cn.itcast.mqtest;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;

public class MQConsumers {
	
	@Test
	public void consumers() throws JMSException{
		
		ConnectionFactory factory = new ActiveMQConnectionFactory();
		Connection connection = factory.createConnection();
		connection.start();
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Queue queue = session.createQueue("helloword");
		MessageConsumer consumer = session.createConsumer(queue);
		/*while(true){
			TextMessage message = (TextMessage) consumer.receive(1000);
			if(message!=null){
				System.out.println(message.getText());
			}else{
				break;
			}
		}*/
		
		//使用监听器来操作
		consumer.setMessageListener(new MessageListener() {
			
			@Override
			public void onMessage(Message message) {
				TextMessage textMessage=(TextMessage)message;
				try {
					System.out.println(textMessage.getText());
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		});
		
		while(true){
			
		}
	}
}
